var api = require('../config/api.js');

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatTimeNotYear(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return  [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 封封微信的的request
 */
function request(url, data, method, header = false) {
  wx.showLoading({
    title: '加载中',
  })
  //获取用户unionid
  var unionid = wx.getStorageSync('userInfo').unionid 
  if (!unionid){
    wx.login({
      success: function (res) {
        if(res.code){
          wx.request({
            url: api.UpdateUnionidInfoURL,
            data: res.code,
            method: "POST",
            header: {
              'Content-Type': 'application/json'
            },
            success: function (res) {
              if(res.data.code == 200){
                let userInfo = wx.getStorageSync('userInfo');
                if (userInfo){
                  userInfo.unionid = res.data.result;
                  wx.setStorageSync('userInfo', userInfo);
                }
              }
            }
          })
        }
      }
    })
  }
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': method == 'GET' || header ? 'application/json' : "application/x-www-form-urlencoded",
        'X-Nideshop-Token': wx.getStorageSync('token')
      },
      success: function (res) {
        wx.hideLoading();
        if (res.statusCode == 200) {
          if (res.data.errno == 401) {
            //未登录跳转登录页

            // let code = null;
            // return login().then((res) => {
            // code = res.code;
            // return getUserInfo();
            // }).then((userInfo) => {
            // //登录远程服务器
            // request(api.AuthLoginByWeixin, { code: code, userInfo: userInfo }, 'POST').then(res => {
            // if (res.errno === 0) {
            // //存储用户信息
            // wx.setStorageSync('userInfo', res.data.userInfo);
            // wx.setStorageSync('token', res.data.token);
            // resolve(res);
            // } else {
            // reject(res);
            // }
            // }).catch((err) => {
            // reject(err);
            // });
            // }).catch((err) => {
            // reject(err);
            // })
            wx.redirectTo({
              url: '/myPages/authorize/authorize'
            })
          } else {
            resolve(res.data);
          }
        } else if (res.data.code == 400) {
          resolve(res);
        } else {
          reject(res.errMsg);
        }

      },
      fail: function (err) {
        reject(err)
        console.log("failed")
      }
    })
  });
}

/**
 * 检查微信会话是否过期
 */
function checkSession() {
  return new Promise(function (resolve, reject) {
    wx.checkSession({
      success: function () {
        resolve(true);
      },
      fail: function () {
        reject(false);
      }
    })
  });
}

/**
 * 调用微信登录
 */
function login() {
  return new Promise(function (resolve, reject) {
    wx.login({
      success: function (res) {
        if (res.code) {
          //登录远程服务器
          console.log(res)
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function (err) {
        reject(err);
      }
    });
  });
}

function getUserInfo() {
  return new Promise(function (resolve, reject) {
    wx.getUserInfo({
      withCredentials: true,
      success: function (res) {
        console.log(res)
        resolve(res);
      },
      fail: function (err) {
        reject(err);
      }
    })
  });
}

function redirect(url) {

  //判断页面是否需要登录
  if (false) {
    wx.redirectTo({
      url: '/pages/auth/login/login'
    });
    return false;
  } else {
    wx.redirectTo({
      url: url
    });
  }
}

function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    image: '/static/images/icon_error.png'
  })
}

function getOrderStatus(number){
  let text = "未知状态"
  switch (number){
    case 1:
      text="未支付"
      break;
    case 2:
      text = "已支付"
      break;
    case 3:
      text = "失效订单"
      break;
    case 4:
      text = "导师接单"
      break;
    case 5:
      text = "已交易"
      break;
    case 6:
      text = ".取消订单"
      break;
    case 7:
      text = "退款订单"
      break;
    case 8:
      text = "待评价"
      break;
    case 9:
      text = "评价完成"
      break;
  }
  return text
}

module.exports = {
  formatTime,
  request,
  redirect,
  showErrorToast,
  checkSession,
  login,
  getUserInfo,
  formatTimeNotYear,
  getOrderStatus
}


